/*******************************************************************

    Author: Xiao
    Date: 2022/3/29 9:06

*******************************************************************/

package utils

import (
	"fmt"
	"golang.org/x/text/encoding/simplifiedchinese"
	"golang.org/x/text/transform"
	"io/ioutil"
	"mcr/pkg/logs"
	"net/http"
	"regexp"
	"strings"
	"time"
)

// 获取签名
func GetOneRemark() string {
	cli := http.Client{
		Timeout: 5 * time.Second,
	}
	req, err := http.NewRequest("GET", "http://guozhivip.com/yy/api/api.php", nil)
	if err != nil {
		logs.Log.Errorf("获取签名错误:%s", err)
		return "每个人都应该有签名,但偏偏我没有."
	}
	rsp, err := cli.Do(req)
	if err != nil {
		logs.Log.Errorf("获取签名错误:%s", err)
		return "每个人都应该有签名,但偏偏我没有."
	}
	defer rsp.Body.Close()
	body, err := ioutil.ReadAll(rsp.Body)
	if err == nil {
		re := regexp.MustCompile(`(?s)\"(.*)\"`)
		m := re.FindAllStringSubmatch(string(body), -1)
		if m != nil {
			return m[0][1]
		}
	}
	return "每个人都应该有签名,但偏偏我没有."
}

// 获取地址信息
func GetAddrPath(addr string) string {
	cli := http.Client{
		Timeout: 5 * time.Second,
	}
	req, err := http.NewRequest("GET", "https://whois.pconline.com.cn/ip.jsp?ip="+addr, nil)
	if err != nil {
		logs.Log.Errorf("获取地址信息失败:%s", err)
		return "中国"
	}
	res, err := cli.Do(req)
	if err != nil {
		logs.Log.Errorf("获取地址信息失败:%s", err)
		return "中国"
	}
	defer res.Body.Close()
	O := transform.NewReader(res.Body, simplifiedchinese.GBK.NewDecoder())
	body, err := ioutil.ReadAll(O)
	if err == nil {
		out := strings.Replace(string(body), "\n", "", -1)
		out = strings.Replace(string(out), "\r", "", -1)
		return out
	}

	return "中国"
}

func GetWebsocketTicket(account string, channel interface{}) string {
	old := fmt.Sprintf("account%schannel%vsalt%v", account, channel, channel)
	return EncodeBySalt(old, "socket")
}

// 判断是不是管理员
func GetIsAdmin(group int) bool {
	var adminsGroups = []int{1}
	for _, ag := range adminsGroups {
		if ag == group {
			return true
		}
	}
	return false
}
